import { _decorator, Component, Node, Collider2D, Contact2DType, IPhysics2DContact, Animation, Sprite, Prefab, RigidBody2D, ERigidBody2DType, isValid, Vec2 } from 'cc';
import { AwardManager } from './AwardManager';
import { GameSceneUI, GameState } from './GameSceneUI';
const { ccclass, property } = _decorator;

@ccclass('Brick')
export class Brick extends Component {
    @property(Animation)
    anim:Animation = null;

    collider:Collider2D = null;
    
    brickID:number = 0;

    alreadyContac:boolean  =false;

    start() {
        this.collider = this.getComponent(Collider2D);
        if (this.collider) {
            this.collider.on(Contact2DType.BEGIN_CONTACT, this.onBeginContac, this);
        }
    }

    onDestroy() {
        if (this.collider) {
            // 注销碰撞回调
            this.collider.off(Contact2DType.BEGIN_CONTACT, this.onBeginContac, this);
        }
    }

    onBeginContac(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null){
         // 获取 otherCollider 的节点
        const otherNode = otherCollider.node;
        // 获取节点的名称
        if(otherNode.name == "lifeLine")
        {
            GameSceneUI.getInstance().GameOver(false);
            return;
        }

        selfCollider.enabled = false;
        selfCollider.body.sleep();
        if(this.alreadyContac)
        {
            console.warn("方块重复触发了碰撞回调");
            return;
        }

        this.alreadyContac = true;

        if(GameSceneUI.getInstance().getGameState() != GameState.running)
        {
            console.warn("方块触发了碰撞回调 游戏已经结束，碰撞无效");
            return;
        }

        this.anim.play();
        const sprite = this.getComponent(Sprite);
        sprite.enabled = false;
        this.collider.enabled=false;

        const awardManager = AwardManager.getInstance();
        if(awardManager == null)
        {
            console.error("awardManager is NULL")
        }
        else
        {
            awardManager.CreateAward(this.node.position.x,this.node.position.y);
        }

        // 延迟一帧删除
        this.scheduleOnce(() => {
            if(isValid(this.node))
            {
                //this.node.active = false;
            }
        });
    }

    public setBrickID(ID:number)
    {
        this.brickID = ID;
    }

    public getBrickID():number{
        return this.brickID;
    }
}


